﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AForge.Video.DirectShow;
using System.Drawing;
using AForge.Video;
using System.IO;
using System.Drawing.Imaging;
using System.Threading;
using Utilidades;
using Modelo;
namespace Interfaz
{
    /// <summary>
    /// Interaction logic for Registrar.xaml
    /// </summary>
    public partial class Registrar : UserControl
    {
        private bool ExisteDispositivo = false;
        Persona persona;
        private FilterInfoCollection DispositivoDeVideo;
        private VideoCaptureDevice FuenteDeVideo = null;
        public Registrar()
        {
            InitializeComponent();
            CargarHoras();
            BuscarDispositivos();
            cargarImagen();
        }
        public void CargarHoras()   
        {
            for (int i = 0; i < 24; i++)
            {
                if (i < 10)
                {
                    comboBox3.Items.Add("0" + Convert.ToString(i));
                    comboBox5.Items.Add("0" + Convert.ToString(i));
                }
                else
                {
                    comboBox3.Items.Add(i);
                    comboBox5.Items.Add(i);
                }
            }
            for (int i = 0; i < 60; i++)
            {
                if (i < 10)
                {
                    comboBox4.Items.Add("0" + Convert.ToString(i));
                    comboBox6.Items.Add("0" + Convert.ToString(i));
                }
                else
                {
                    comboBox4.Items.Add(i);
                    comboBox6.Items.Add(i);
                }
            }
        }
        public void cargarImagen()
        {
            BitmapImage logo = new BitmapImage();
            logo.BeginInit();
            logo.UriSource = new Uri("Imagenes/d_silhouette_Bart_Simpson.jpg", UriKind.Relative);
            logo.EndInit();
            image1.Source = logo;
        }
        public void BuscarDispositivos()
        {
            DispositivoDeVideo = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (DispositivoDeVideo.Count == 0)
            {
                ExisteDispositivo = false;
                button1.IsEnabled = false;
            }
            else
            {
                ExisteDispositivo = true;
                CargarDispositivos(DispositivoDeVideo);

            }
        }
        public void CargarDispositivos(FilterInfoCollection Dispositivos)
        {
            for (int i = 0; i < Dispositivos.Count; i++) ;
            comboBox2.Items.Add(Dispositivos[0].Name.ToString());
            comboBox2.SelectedIndex = 0;
        }
        public void TerminarFuenteDeVideo()
        {
            if (!(FuenteDeVideo == null))
                if (FuenteDeVideo.IsRunning)
                {
                    FuenteDeVideo.SignalToStop();
                    FuenteDeVideo = null;
                }

        }
        void Video_NuevoFrame(object sender, NewFrameEventArgs eventArgs)
        {

            System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();

            MemoryStream ms = new MemoryStream();
            imgforms.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);

            bi.StreamSource = ms;
            bi.EndInit();

            bi.Freeze();
            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                image1.Source = bi;
            }));

        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (ExisteDispositivo)
            {
                button2.IsEnabled = false;
                button3.IsEnabled = false;
                comboBox2.IsEnabled = false;
                FuenteDeVideo = new VideoCaptureDevice(DispositivoDeVideo[comboBox2.SelectedIndex].MonikerString);
                FuenteDeVideo.NewFrame += new NewFrameEventHandler(Video_NuevoFrame);
                FuenteDeVideo.Start();
                button1.Visibility = Visibility.Hidden;
                button4.Visibility = Visibility.Visible;
            }
        }
        public Byte[] BufferFromImage(BitmapImage imageC)
        {
            MemoryStream memStream = new MemoryStream();
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(imageC));
            encoder.Save(memStream);
            return memStream.GetBuffer();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (persona == null)
                    throw new Exception("Seleccione un empleado");
                if (comboBox3.Text == "" || comboBox6.Text == "" || comboBox5.Text == "" || comboBox4.Text == "")
                    throw new Exception("Debe especificar el rango de las horas en las que el usuario podra entrar al sistema");
                if(validarTodos())
                {
                    System.Windows.Controls.ComboBoxItem curItem = ((System.Windows.Controls.ComboBoxItem)comboBox1.SelectedItem);
                    DateTime horaEntrada = new DateTime(2012,12,12,Convert.ToInt32(comboBox3.Text),Convert.ToInt32(comboBox4.Text),0);
                    DateTime horaSalida = new DateTime(2012, 12, 12, Convert.ToInt32(comboBox5.Text), Convert.ToInt32(comboBox6.Text), 0);
                    string cmbvalue = curItem.Content.ToString();
                    DateTime fec = DateTime.Now.Date;

                    Procesos.GestorRegistro.registrarCuenta(persona.Ci, textBox7.Text, passwordBox1.Password, BufferFromImage((BitmapImage)image1.Source), cmbvalue, fec, horaEntrada, horaSalida);
                        MessageBox.Show("Registro con exito", "Exito", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    // cargarImagen();
                }
                else
                    MessageBox.Show("Error, revise los campos marcados con rojo","Error",MessageBoxButton.OK,MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            button4.Visibility = Visibility.Hidden;
            button1.Visibility = Visibility.Visible;
            TerminarFuenteDeVideo();
            comboBox2.IsEnabled = true;
            button2.IsEnabled = true;
            button3.IsEnabled = true;
        }


        private void textBox8_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            uint iValue = 0;

            if (UInt32.TryParse(textBox.Text, out iValue) == false)
            {
                TextChange textChange = e.Changes.ElementAt<TextChange>(0);
                int iAddedLength = textChange.AddedLength;
                int iOffset = textChange.Offset;

                textBox.Text = textBox.Text.Remove(iOffset, iAddedLength);
            }
        }
        public void setMensaje(TextBox text, string mensaje)
        {
           
           
                text.Background = System.Windows.Media.Brushes.Red;
            
           
            text.ToolTip = mensaje;
         
        }
        public void setMensajePass(PasswordBox text, string mensaje)
        {


            text.Background = System.Windows.Media.Brushes.Red;


            text.ToolTip = mensaje;

        }
       

        private void textBox8_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox text = sender as TextBox;
            text.ToolTip = null;
            text.Background = System.Windows.Media.Brushes.White;
        }





       
       
       
       

       

        public bool validarPasswordBox1()
        {
            try
            {
                Procesos.Validar.validarPassword(passwordBox1.Password);
                return true;
            }
            catch (Exception ex)
            {
                setMensajePass(passwordBox1, ex.Message);
                return false;
            }
        }
        private void passwordBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            validarPasswordBox1();
        }
        public bool validarTextBox7()
        {
            try
            {
                Procesos.Validar.validarVacio(textBox7.Text);
                return true;
            }
            catch (Exception ex)
            {
                setMensaje(textBox7, ex.Message);
                return false;
            }
        }
        private void textBox7_LostFocus(object sender, RoutedEventArgs e)
        {
            validarTextBox7();
        }

   
        public bool validarPasswordBox2()
        {
            try
            {
                Procesos.Validar.validarPasswordsIguales(passwordBox1.Password, passwordBox2.Password);
                return true;
            }
            catch (Exception ex)
            {
                setMensajePass(passwordBox2, ex.Message);
                return false;
            }
        }
        private void passwordBox2_LostFocus(object sender, RoutedEventArgs e)
        {
            validarPasswordBox2();
        }

        private void passwordBox1_GotFocus(object sender, RoutedEventArgs e)
        {
            PasswordBox text = sender as PasswordBox;
            text.ToolTip = null;
            text.Background = System.Windows.Media.Brushes.White;
        }
        public bool validarTodos()
        {
            bool   t1 = validarTextBox7(), p1 = validarPasswordBox1(), p2 = validarPasswordBox2();
            return (t1 && p1 && p2);
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            persona = new Persona();
            BuscarEmpleado buscar = new BuscarEmpleado(persona);
            buscar.ShowDialog();
            label2.Content = persona.Ci;
        }
    }
}
